package com.gexiaobao.pigeon.ui.view

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText

/**
 * @Author      : hxw
 * @Date        : 2023/4/27 17:33
 * @Describe    :
 */
class MyTextWatcher(private val decimalDigits: Int, private val editText: AppCompatEditText) : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        val text = s?.toString()
        if (text == ".") {
            //第一位不能位 .
            editText.setText("")
        } else if (text == "00") {
            //不能输入00
            editText.setText("0")
            editText.setSelection(1)
        } else if (!text.isNullOrEmpty()) {
            val decimalArray = text.split(".")
            if (decimalArray.size == 2) {
                //存在小数点后 限制最大输入长度
                val decimal = decimalArray[1]
                //限制最大长度为当前文本长度+(限制小数位数-已输入的小数位数)
                editText.setMaxLength(text.length + (decimalDigits - decimal.length))
            } else {
                //没有小数点设置最大位数为100
                editText.setMaxLength(100)
            }
        }
    }
    private fun TextView.setMaxLength(length:Int){
        this.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(length))
    }
}